from django.shortcuts import render, redirect
from crm import models
from crm.forms import RegForm
from rbac.service.init_permission import init_permission
import hashlib


# 登录
def login(request):
    error = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        hashlib.md5().update(password.encode('utf-8'))
        password = hashlib.md5().hexdigest()
        obj = models.UserProfile.objects.filter(username=username, password=password).first()
        if obj:
            request.session['pk'] = obj.pk
            init_permission(obj, request)
            return redirect('crm:customer_list')
        error = '账号或密码错误'
    return render(request, 'login.html', {'error': error})


# 注册
def reg(request):
    obj = RegForm()
    if request.method == 'POST':
        obj = RegForm(request.POST)
        if obj.is_valid():
            obj.save()
            return redirect('crm:login')
    return render(request, 'reg.html', {'obj': obj})
